package com.example.demo.interceptor;

import com.example.demo.common.ErrorCode;
import com.example.demo.constant.CommonConstant;
import com.example.demo.context.UserContext;
import com.example.demo.exception.BusinessException;
import com.example.demo.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class AdminInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtUtils jwtUtils;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        // 获取请求头中的token
        String token = request.getHeader("Admin-Token");
        if (token == null || token.isEmpty()) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }

        // 验证token
        Claims claims = jwtUtils.getClaimsByToken(token, CommonConstant.UserType.ADMIN);
        if (claims == null) {
            throw new BusinessException(ErrorCode.ADMIN_TOKEN_INVALID);
        }
        Long id= Long.parseLong(claims.get("id").toString());
        UserContext.setUserId(id);
        return true;
    }
} 